package com.fushenlan.commons;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 校验参数工具类
 *
 * @author Administrator
 * @date 2022/4/21 14:49
 */
@Slf4j
public class CheckParamUtil {

    /**
     * 校验字段值不为空，包含父类对象属性字段
     *
     * @param obj         待校验对象
     * @param checkFields 对象属性字段名
     */
    public static String checkNull(Object obj, List<String> checkFields) {
        if (Objects.isNull(obj)) {
            return "请传入校验对象";
        }
        if (CollectionUtil.isEmpty(checkFields)) {
            return "请传入校验字段名";
        }

        //递归获取包括父类的所有字段
        List<Field> fieldList = new ArrayList<>();
        Class<?> objClass = obj.getClass();
        while (objClass != null) {
            fieldList.addAll(Arrays.asList(objClass.getDeclaredFields()));
            objClass = objClass.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);

        StringBuilder sb = new StringBuilder();
        String fieldName = "";
        try {
            for (String checkField : checkFields) {
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (checkField.equals(field.getName())) {
                        Object o = field.get(obj);
                        if (o == null || "".equals(o.toString())) {
                            //使用注解@ApiModelProperty的value值
                            ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                            if (annotation != null) {
                                fieldName = annotation.value();
                            } else {
                                fieldName = field.getName();
                            }
                            sb.append("请录入[").append(fieldName).append("]").append("必传信息");
                            log.info("参数校验结果：{}", sb);
                            return sb.toString();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("字段校验异常", e);
            throw new RuntimeException(e);
        }
        return null;
    }
}
